<?php
 class ApiCenter_ProductApi_Model_Api2_Product_Save_Rest extends ApiCenter_ProductApi_Model_Api2_Product_Save{
     
     const ATTRIBUTE_CODE = 'media_gallery';
      
     const DEFULT_VISIBILITY = "1";
     
     const DEFULT_STAUTS = "2";
     
     const DEFULT_APPROVAL = "0";
      
     const  STOREID = "0";
      
     /**
      * 验证并获取商家信息
      *
      * @param unknown $vendorId*/
     protected  function _loadVendor($vendorId){
         $vendor =  Mage::getModel("vendors/vendor")->load($vendorId);
         if(!$vendor->getId()){
             $this->_critical("商家信息错误",400);
         }
         Mage::register("current_vendor", $vendor);
         return $vendor;
     }
     /**
      * 自动合并生成新的子产品
      * */
     protected function _automaticallyChildPro($mainProduct,$select_super){
         $childinfo=$mainProduct['child_products'];
         $childWeight = array();
         
         Mage::log("获得子产品的数组",1,"upload.log");
         Mage::log($childinfo,1,"upload.log");
         
         if(empty($childinfo)){
             $this->_critical("子产品必须大于至少一个",400);
         }
         unset($mainProduct['child_products']);    
         unset($mainProduct['entity_id']);
         
         if(isset($mainProduct['images'])){
             unset($mainProduct['images']);
         }
         $this->validateChildProduct($childinfo,$select_super);//验证子数据
         
         
         foreach ($childinfo as $k=> $v){
             $childWeight[] =$v['weight'];
             foreach ($mainProduct as $val){
                 $childProduct[$k]= $v+$mainProduct;
                 $childProduct[$k]["visibility"] =self::DEFULT_VISIBILITY;
                 $childProduct[$k]["url_key"] =false;
             }  
         }
         Mage::register("childweight", $childWeight);
         return $childProduct;
     }
      
      
     public  function getConfigAttrCode($attributeSetId,$select=array(),$simpleProductArr,$attrprice){
         try {
             $edit =false;
             if($id=$this->getRequest()->getParam("id")){
                 $edit =$id;
                 unset($id);
             }
             
             $AttributeCode   =array();
             $attributes = Mage::getModel('catalog/product_attribute_api')->items($attributeSetId);
             foreach($attributes as $_attribute)
             {
                 if($_attribute['scope'] == 'global' && $_attribute['type'] == 'select')
                 {
                     $super_attribute = Mage::getModel('eav/entity_attribute')->loadByCode('catalog_product',$_attribute['code']);
                     if($super_attribute->getIsConfigurable() == 1)
                     {
                         $AttributeCodeData[] = $super_attribute->getData();
                     }
                 }
             }
               Mage::log("获取可配置数据-具有的超级属性",1,"upload.log");
               Mage::log($AttributeCodeData,1,"upload.log");
               
               Mage::log("获取可配置数据-已经上传产品的数据",1,"upload.log");
               Mage::log($simpleProductArr,1,"upload.log");
               
             $simpleProducts = Mage::getResourceModel('catalog/product_collection')
             ->addIdFilter($simpleProductArr);
              
             foreach ($select as $val){
                 $simpleProducts -> addAttributeToSelect($val);
             }
             foreach ($AttributeCodeData as  $configurableAtt){
                 foreach ($select as $attribute_code ){
                     if($configurableAtt['attribute_code'] == $attribute_code ){
                         foreach ($simpleProducts as $simple){
                             $productinfo = array(
                                 'label' => $simple->getAttributeText($configurableAtt['attribute_code']),
                                 'attribute_id' => $configurableAtt['attribute_id'],
                                 'value_index' => (int) $simple->getData($attribute_code),
                                 'is_percent' => 0,
                                 'pricing_value' => 0
                             );
                             $values[$attribute_code][$simple->getData($attribute_code)]= $productinfo;
                             $configurableProductsData[$simple->getId()][] = $productinfo;
                         }
                          
                         $configurableAttributesData[] = array(
                             'use_default' =>"1",
                             'label'          => $configurableAtt['frontend_label'],
                             'position'       => $configurableAtt['position'],
                             'values'         => $values[$attribute_code]?$values[$attribute_code]:array(),
                             'attribute_id'   => $configurableAtt['attribute_id'],
                             'attribute_code' =>  $configurableAtt['attribute_code'],
                             'frontend_label' =>$configurableAtt['frontend_label'],
                         );
                     }
                 }
             }

             foreach ($configurableAttributesData as $key => $attrcode){
                    foreach ($attrprice as   $_attrprice){
                        if($attrcode['attribute_code'] == $_attrprice["attribute_code"]){
                            if($edit&&isset($_attrprice["id"])){
                                $configurableAttributesData[$key]["id"]=$_attrprice["id"];
                            }
                            foreach ($_attrprice['value'] as $num => $price){
                                $configurableAttributesData[$key]["values"][$num]["pricing_value"]=$price;
                            }
                        }
                    }
             }
             
             $configurableKey['configurable_attributes_data'] = $configurableAttributesData;
             $configurableKey['configurable_products_data']  = $configurableProductsData;
              
             return $configurableKey;//返回用户所绑定的属性
              
         } catch (Mage_Core_Exception $e) {
             Mage::log('DEBUG_ERROR');
             $this->_critical('system_error_contactmonkey');
         }
     
     }
     /**
      *
      * 保存产品
      * */
     protected  function saveProduct($type,$set,$productData,$store = null ) {
         try {
             
             $edit = false;//是否是编辑产品
             
            $accept_productId =$this->getRequest()->getParam("id");
            if(!empty($accept_productId)){
                $edit = true;
            }
             $vendor = Mage::registry("current_vendor");
             $vendors_info = $vendor->getData();
             //验证数据
             $this->validateProduct($productData, $type,$set);
             $sku_final = $vendors_info['vendor_id']."_".$productData['vendor_sku']
             ;
             /*@var $product Mage_Catalog_Model_Product */
             if(!$edit){
                 $product = Mage::getModel('catalog/product');
             }else{
                 $pId = isset($productData['entity_id'])?$productData['entity_id']:null;
                 if($pId){
                     $product = Mage::getModel('catalog/product')->setStoreId(self::STOREID)->load($pId);

                 }else{
                     $product = Mage::getModel('catalog/product');
                 }
                $product->setUpdatedAt(now());
             }

             //预处理数据
            
             $this->_prepareDataForSave($product, $productData,$type);

             $product->setStoreId(self::STOREID)
             ->setAttributeSetId($set)
             ->setTypeId($type)
             ->setSku( $sku_final);
             
             if(!isset($product['media_gallery'])||!is_array($product['media_gallery'])){
                 foreach ($product->getMediaAttributes() as $mediaAttribute) {
                     $mediaAttrCode = $mediaAttribute->getAttributeCode();
                     $product->setData($mediaAttrCode, 'no_selection');
                 }
             }    
           
             return $product;
         } catch (Exception $e) {
             Mage::log("数据保存过程报错",1,"upload-error.log");
             Mage::log($productData,1,"upload-error.log");
             Mage::log("保存前错误信息:".$e->getMessage(),1,"upload-error.log");
             $this->_critical($e->getMessage(),400);
         }
     }
 }